package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.OrderItemMapper;
import com.jt.mapper.OrderMapper;
import com.jt.mapper.OrderShippingMapper;
import com.jt.pojo.Order;
import com.jt.pojo.OrderItem;
import com.jt.pojo.OrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DubboOrderServiceImpl implements DubboOrderService{


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderShippingMapper orderShippingMapper;

    //订单入库
    @Override
    @Transactional
    public String saveOrder(Order order) {
        //orderId由登录用户id+当前时间戳
        String orderId = "" + order.getUserId() + System.currentTimeMillis();
        //1.完成订单入库操作
        order.setOrderId(orderId).setStatus(1).setCreated(new Date()).setUpdated(order.getCreated());
        orderMapper.insert(order);

        //2.完成订单商品入库
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(orderId).setCreated(new Date()).setUpdated(order.getCreated());
            orderItemMapper.insert(orderItem);
        }

        //3.完成订单物流入库
        OrderShipping orderShipping = order.getOrderShipping();
        orderShipping.setOrderId(orderId).setCreated(new Date()).setUpdated(order.getCreated());
        orderShippingMapper.insert(orderShipping);

        return orderId;
    }

    //订单结算页显示详细信息
    @Override
    public Order findOrderById(String id) {
        Order order = orderMapper.selectById(id);
        OrderShipping orderShipping = orderShippingMapper.selectById(id);
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",id);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        return order.setOrderItems(orderItems).setOrderShipping(orderShipping);
    }
}
